
import os
import sys
# from dotenv import set_key

import codecs
import fileinput
import io

__escape_decoder = codecs.getdecoder('unicode_escape')

def decode_escaped(escaped):
    return __escape_decoder(escaped)[0]

def parse_line(line):
    line = line.strip()

    # Ignore lines with `#` or which doesn't have `=` in it.
    if not line or line.startswith('#') or '=' not in line:
        return None, None

    k, v = line.split('=', 1)

    if k.startswith('export '):
        (_, _, k) = k.partition('export ')

    # Remove any leading and trailing spaces in key, value
    k, v = k.strip(), v.strip()

    if v:
        v = v.encode('unicode-escape').decode('ascii')
        quoted = v[0] == v[-1] in ['"', "'"]
        if quoted:
            v = decode_escaped(v[1:-1])

    return k, v

def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"):
    """
    Adds or Updates a key/value to the given .env
    If the .env path given doesn't exist, fails instead of risking creating
    an orphan .env somewhere in the filesystem
    """
    value_to_set = value_to_set.strip("'").strip('"')
    if not os.path.exists(dotenv_path):
        # warnings.warn("can't write to %s - it doesn't exist." % dotenv_path)
        return None, key_to_set, value_to_set

    if " " in value_to_set:
        quote_mode = "always"

    line_template = '{}="{}"' if quote_mode == "always" else '{}={}'
    line_out = line_template.format(key_to_set, value_to_set)

    replaced = False
    for line in fileinput.input(dotenv_path, inplace=True):
        k, v = parse_line(line)
        if k == key_to_set:
            replaced = True
            line = "{}\n".format(line_out)
        print(line, end='')

    if not replaced:
        with io.open(dotenv_path, "a") as f:
            f.write("{}\n".format(line_out))

    return True, key_to_set, value_to_set

def add_ssid(ssid, psk):
  network = '\nnetwork='
  ssid = '\tssid="%s"' % ssid
  if psk is None:
    psk = ''
    key_mgmt = '\tkey_mgmt=NONE'
  else:
    psk = '\tpsk="%s"' % psk
    key_mgmt = '\tkey_mgmt=WPA-PSK'
  network = network + '{\n' + ssid + '\n' + psk + '\n' + key_mgmt + '\n}'
  with open('wpa_supplicant.conf', 'a') as conf:
    conf.write(network)

def set_env(key, val, quote_mode='always'):
  env_path = './.env'
  set_key(env_path, key, val, quote_mode)

def connect_wireless_with_wpa(interface_name, ssid, key):
  """
  连接WPA加密的无线网
  """
  if os.geteuid():
    args = [sys.executable] + sys.argv
    # 下面两种写法，一种使用su，一种使用sudo，都可以
    #os.execlp('su', 'su', '-c', ' '.join(args))
    os.execlp('sudo', 'sudo', *args)
  os.system('wpa_cli -i %s add_network' % interface_name)
  os.system('wpa_cli -i %s set_network 0 ssid \'"%s"\'' % (interface_name, ssid))
  os.system('wpa_cli -i %s set_network 0 key_mgmt WPA-PSK' % interface_name)
  os.system('wpa_cli -i %s set_network 0 psk \'"%s"\'' % (interface_name, key))
  os.system('wpa_cli -i %s enable_network 0' % interface_name)

if __name__ == "__main__":
  # import reboot
  ssid = "zhongyi_office",
  psk = "123123one",
  # add_ssid(ssid, psk)
  # reboot.shutdown()
  set_env('wsUrl', 'ws://47.96.179.13:9091/websocket/manual')
  set_env('restUrl', 'http://47.96.179.13:9091/manual')
  set_env('id', '1004', quote_mode=False)
